##JS basic
const cities =[]
fetch(endpoint) -> 返回promise而非data
.then(blob => blob.json()) 再返回一個promise
.then(data => cities.push(...data))
function findMatches(wordToMatch, cities){
return cities.filter(place => {
con regex = new RegExp(wordToMatch, 'gi')
return place.city.match(regex) || place.state.match(regex)
})
}
function numberWithCommas(x){
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
function displayMatches(){
const matchArray = findMatches(this.value, cities)
const html = matchArray.map(place => {
const regex = new RegExp(this.value, 'gi')
const cityName = place.city.replace(regex, `<span class = 'h1'>${this.value}</span>`
const stateName = place.state.replace(regex, `<span class = 'h1'>${this.value}</span>`
return `
<li>
<span class='name'>${cityName}, ${stateName}</span>
<span class='population'>${numberWithCommas(place.population)}</span>
</li>
`
}).join('')
suggestions.innerHTML = html
}
const searchInput = document.querySelector('.search')
const suggestion = document.querySelector('.suggestions')
searchInput.addEventListener('changed', displayMatches)
searchInput.addEventListener('keyup', displayMatches)
##前端